#coding=utf-8
from django.db import models
from stutils import todec

class Price(models.Model):
    exday = models.ForeignKey('Exday', unique=True)
    
    start = models.DecimalField( max_digits=8, decimal_places=2, null=True, blank=True)
    end = models.DecimalField( max_digits=8, decimal_places=2, null=True, blank=True)
    
    low = models.DecimalField( max_digits=8, decimal_places=2, null=True, blank=True)
    high = models.DecimalField( max_digits=8, decimal_places=2, null=True, blank=True)
    
    volume = models.IntegerField()
    amount = models.IntegerField()
    
    change = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True )
    hsl = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True )
    fluctuation = models.DecimalField( max_digits=6, decimal_places=2, null=True, blank=True )
    
    def get_change(self):
        '''涨跌'''  
        pre = self.exday.pre
        if not pre:return None
        
        pe = pre.price.end
        change = ( self.end - pe )/ pe * 100
        change = todec(change, 2)
        
        return change
    
    def get_hsl(self):
        '''换手率'''
        d = self.exday.date.isoformat()
        ts = self.exday.ts
        if not ts:
            #like 爱使股份(600652) in ipo day no 流通A股数量信息fromsina
            return None
        hsl = self.volume / float(ts) * 100
        hsl = todec(hsl, 2)
        
        return hsl
        
    def get_fluctuation(self):
        '''波动幅度'''
        f = ( self.high - self.low ) / self.end * 100
        f = todec(f, 2)
        return f
        
    def save(self):
        self.change = self.get_change()   
        self.hsl = self.get_hsl()
        self.fluctuation = self.get_fluctuation()
        super(Price, self).save()
    
    def get_date(self):
        return self.exday.date.isoformat()
    date = property(fget=get_date)
    
    def get_atr(self):
        '''真实波动幅度'''
        pre = self.exday.pre
        if not pre:return None
        pde = pre.price.end
        #print pde
        return max(self.high-self.low, self.high-pde, pde-self.low)
    atr = property(fget=get_atr)
    
    def get_N(self):
        '''真实波动幅度 20天简单平均值'''
        atrs = []
        p = self
        for i in range(20):
            a = p.atr
            if not a:return None
            atrs.append(a)
            
            p = p.exday.pre.price
        return todec(float(sum(atrs))/20.0, 2)
    N = property(fget=get_N)
    
    def get_jump(self):
        pre = self.exday.pre
        if not pre:return None
        
        pre_end = pre.price.end
        jump = todec( (self.start-pre_end)*100/pre_end , 2)
        return jump
    jump = property(fget=get_jump)
    
    def __unicode__(self):
        jyr = unicode('交易日', 'u8')
        jgxx = unicode('的价格信息', 'u8')
        
        return "%s%s on %s(%s)"%(self.exday.share.name, jgxx, jyr, self.exday.date)
        
    class Admin:pass
    class Meta:
        app_label = 'stock'